package com.example.avplayer;

import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.os.Environment;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class H264CameraEncode {
    MediaCodec mediaCodec;
    int width;
    int height;
    int index;// 帧顺序
    public H264CameraEncode(int width,int height) throws IOException {
         mediaCodec = MediaCodec.createEncoderByType("video/avc");

        MediaFormat mediaFormat = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height);
        // 码率 单位时间内
        mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE,width * height);
        mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE,20);
        mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL,30);
        mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible);
        mediaCodec.configure(mediaFormat,null,null,MediaCodec.CONFIGURE_FLAG_ENCODE);
        mediaCodec.start();
    }


    public void encodeFrame(byte[] input) {
        int bufferIndex  = mediaCodec.dequeueInputBuffer(10000);
        if (bufferIndex >= 0) {
            ByteBuffer outputBuffer = mediaCodec.getInputBuffer(bufferIndex);
            outputBuffer.put(input);
            mediaCodec.queueInputBuffer(bufferIndex,0,input.length,computPts(),0);
            index++;
        }
        // 输出到文件
        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
        int outbufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 10000);
        if (outbufferIndex >= 0) {
            ByteBuffer outputBuffer = mediaCodec.getOutputBuffer(outbufferIndex);
            byte[] bytes = new byte[outputBuffer.remaining()];
            outputBuffer.get(bytes);
            writeFile(bytes);
            mediaCodec.releaseOutputBuffer(outbufferIndex,false);
        }

    }

    private void  writeFile(byte[] ba) {
        // 打开输入流
        String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/cameraCodec.h264";
        FileOutputStream fileOutputStream = null;
        try {
            // append 文件后面
            fileOutputStream = new FileOutputStream(path,true);
            fileOutputStream.write(ba);
        } catch (IOException e) {
            e.printStackTrace();
            if (fileOutputStream!=null) {
                try {
                    fileOutputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

    }
    //    pts      帧率    15帧  1 帧    1000 000 /15   1000 000 /15 *2  1000 000 /15 *3  1000 000 /15 *4   1000 000 /15 *5
    public int computPts() {
        return 1000000 / 20 * index;
    }
}
